
import { registerClass } from "../../../cfw/tools/class_decorator";
import BaseAd from "../../core/base/BaseAd";
import { SDKLogicState, SDKState } from "../../SDKDefine";


@registerClass('WXInsertAd')
export default class WXInsertAd extends BaseAd {



    open(): void {
        this.setLogicState(SDKLogicState.open)
        if (this.isState(SDKState.loadSucess)) {
            this.show()
        } else {
            this.create();
        }
    }



    show(): void {
        this.setLogicState(SDKLogicState.close)
        this.setState(SDKState.show)
        if (this.ad) {
            console.log(' wx insert ad show ', this.adUnitID)
            this.ad.show().catch((err) => {
                console.error(err)
            })
        }
    }


    protected onLoadLogic(): void {
        if (this.isLogicState(SDKLogicState.open)) {

            this.show()
        }
    }


    onClose() {
        this.setState(SDKState.close)
    }

    create() {
        // 创建插屏广告实例，提前初始化
        this.destroy()
        this.setState(SDKState.loading)
        if (!this.ad) {
            console.log(' wx insert ad create ', this.adUnitID)
            this.ad = this.sdk.createInterstitialAd({
                adUnitId: this.adUnitID
            })
            this.ad.onLoad(this.getFunc(this.onLoad))
            this.ad.onError(this.getFunc(this.onError))
            this.ad.onClose(this.getFunc(this.onClose))
        }
    }


    destroy(): void {
        if (this.ad) {
            console.log(' wx insert ad destroy ', this.adUnitID)
            this.ad.offLoad(this.getFunc(this.onLoad))
            this.ad.offError(this.getFunc(this.onError))
            this.ad.offClose(this.getFunc(this.onClose))
            this.ad.destroy();
            this.ad = null;
        }
    }
}
